package com.luanhj.framework.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.luanhj.framework.tenant.TenantContext;
import com.luanhj.framework.tenant.properties.TenantProperties;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import net.sf.jsqlparser.expression.Expression;


/**
 * @author luanhj
 * @date 2025/6/3 15:49
 * @description 多租户插件配置类，支持从配置文件中动态读取忽略的表名和租户字段名
 **/
@Component
public class MybatisPlusTenantConfig {
    @Autowired
    private TenantProperties tenantProperties;

    @Bean
    public TenantLineInnerInterceptor tenantLineInnerInterceptor() {
        if (!tenantProperties.isEnabled()) {
            return new TenantLineInnerInterceptor();
        }

        return new TenantLineInnerInterceptor(new TenantLineHandler() {

            @Override
            public Expression getTenantId() {
                String tenantId = TenantContext.getTenantId();
                return new StringValue("'" + tenantId + "'");
            }


            @Override
            public String getTenantIdColumn() {
                  return tenantProperties.getTenantIdColumn();//TenantLineHandler.super.getTenantIdColumn();
            }

            @Override
            public boolean ignoreTable(String tableName) {
                return tenantProperties.getIgnoreTables().stream()
                        .anyMatch(t -> t.equalsIgnoreCase(tableName));
            }
        });
    }
}
